<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>test websockt</title>
    <style type="text/css" href="/dist/css/vendors/bootstrap.css"></style>
    <script type="text/javascript" src="/dist/js/libs/jquery-1.12.0.min.js"></script>
</head>

<body>
    <div>
        <input id="message">
    </div>
    <table class="table">
        <thead>
            <th>
                <td>symbol</td>
                <td>price</td>
            </th>
        </thead>
        <tbody>
            <tr>
                <td>AAPL</td>
                <td id="AAPL"><span></span></td>
            </tr>
            <tr>
                <td>MSFT</td>
                <td id="MSFT"><span></span></td>
            </tr>
            <tr>
                <td>AMZN</td>
                <td id="AMZN"><span></span></td>
            </tr>
            <tr>
                <td>GOOG</td>
                <td id="GOOG"><span></span></td>
            </tr>
            <tr>
                <td>YHOO</td>
                <td id="YHOO"><span></span></td>
            </tr>
        </tbody>
    </table>
    <script type="text/javascript">
    var ws = new WebSocket("ws://10.2.235.36:8181");
    ws.onopen = function(e) {
        console.log('Connection to server opened');
    }

/*    function sendMessage() {
        ws.send(document.getElementById('message').value);
    }
*/
    /************************************/
    var isClose = false;
    var stocks = {
        "AAPL": 0,
        "MSFT": 0,
        "AMZN": 0,
        "GOOG": 0,
        "YHOO": 0
    };

    var stock_request = {
        stocks:["AAPL","MSFT","AMZN","GOOG","YHOO"]
    }
    function updataUI() {
        ws.onopen = function(e) {
                console.log('Connection to server opened');
                isClose = false;
                ws.send(JSON.stringify(stock_request));   //stock_request
                console.log("sened a mesg");
            }
            //更新UI
        var changeStockEntry = function(symbol, originalValue, newValue) {
                var valElem = $('#' + symbol + ' span');
                valElem.html(newValue.toFixed(2));
                if (newValue < originalValue) {
                    valElem.addClass('label-danger');
                    valElem.removeClass('label-success');
                } else if (newValue > originalValue) {
                    valElem.addClass('label-success');
                    valElem.removeClass('label-danger');
                }
            }
            // 处理受到的消息
        ws.onmessage = function(e) {
            var stocksData = JSON.parse(e.data);
            console.log(stocksData);
            for (var symbol in stocksData) {
                if (stocksData.hasOwnProperty(symbol)) {
                    changeStockEntry(symbol, stocks[symbol], stocksData[symbol]);
                    stocks[symbol] = stocksData[symbol];
                }
            }
        };
    }

    updataUI();
    </script>
</body>

</html>
